package com.slf.demo1;

/**
 * @author: shilvfa
 * @date: 2025-07-13 23:23
 * @email:shilfwh@163.com
 * @Description:
 */
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class FuturesDataProcessor {

    public static Map<String, Double> createPriceMap(String filePath) {
        // 生成时间点列表
        List<Integer> timeList = creTimeList();

        // 存储最终结果: key=TradingDay_UpdateTime, value=LastPrice
        Map<String, Double> resultMap = new LinkedHashMap<>();

        // 存储原始数据: key=时间整数(秒级), value=LastPrice
        Map<Integer, Double> rawDataMap = new TreeMap<>();
        String tradingDay = null;

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            boolean firstLine = true;

            while ((line = br.readLine()) != null) {
                if (firstLine) {
                    firstLine = false;
                    continue; // 跳过标题行
                }

                String[] columns = line.split(",");
                if (columns.length < 5) {
                    continue;
                }

                // 解析交易日
                if (tradingDay == null) {
                    tradingDay = columns[0];
                }

                // 跳过没有价格的数据行
                if (columns[4].isEmpty()) {
                    continue;
                }

                // 解析时间和价格
                String updateTime = columns[2];
                double lastPrice = Double.parseDouble(columns[4]);
                int timeInt = convertTimeToInt(updateTime);

                // 存储最后出现的秒级价格（覆盖同一秒内的早期数据）
                rawDataMap.put(timeInt, lastPrice);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Collections.emptyMap();
        }

        // 如果没有有效交易日数据，返回空map
        if (tradingDay == null || rawDataMap.isEmpty()) {
            return Collections.emptyMap();
        }

        // 获取所有有效时间点并排序
        List<Integer> existingTimes = new ArrayList<>(rawDataMap.keySet());
        Collections.sort(existingTimes);

        // 为每个目标时间点找到最近的价格
        for (int targetTime : timeList) {
            // 直接找到的时间点
            if (rawDataMap.containsKey(targetTime)) {
                String key = tradingDay + "_" + formatTime(targetTime);
                resultMap.put(key, rawDataMap.get(targetTime));
                continue;
            }

            // 寻找最接近的时间点
            int closestTime = findClosestTime(existingTimes, targetTime);
            String key = tradingDay + "_" + formatTime(targetTime);
            resultMap.put(key, rawDataMap.get(closestTime));
        }

        return resultMap;
    }

    // 生成时间点列表
    public static List<Integer> creTimeList() {
        List<Integer> list = new ArrayList<>(961);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 9);
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.SECOND, 0);

        int start = exchange2Integer(calendar);
        int end = 150000;

        while (start <= end) {
            if ((start >= 93000 && start <= 113000) ||
                    (start > 130000 && start <= 150000)) {
                list.add(start);
            }
            calendar.add(Calendar.SECOND, 15);
            start = exchange2Integer(calendar);
        }
        return list;
    }

    // Calendar转换为整数时间
    private static int exchange2Integer(Calendar calendar) {
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        return hour * 10000 + minute * 100 + second;
    }

    // 时间字符串转换为整数
    private static int convertTimeToInt(String timeStr) {
        String clean = timeStr.replace(":", "");
        return Integer.parseInt(clean.substring(0, 6)); // 忽略毫秒部分
    }

    // 格式化时间为6位字符串
    private static String formatTime(int time) {
        return String.format("%06d", time);
    }

    // 在有序列表中查找最接近的时间点
    private static int findClosestTime(List<Integer> times, int target) {
        int idx = Collections.binarySearch(times, target);

        // 找到精确匹配
        if (idx >= 0) {
            return times.get(idx);
        }

        // 计算插入位置
        int insertionPoint = -idx - 1;

        // 处理边界情况
        if (insertionPoint == 0) {
            return times.get(0);
        }
        if (insertionPoint == times.size()) {
            return times.get(times.size() - 1);
        }

        // 比较前后两个时间点
        int prev = times.get(insertionPoint - 1);
        int next = times.get(insertionPoint);

        // 返回更接近的时间点（优先选择较早的时间点）
        return (target - prev <= next - target) ? prev : next;
    }

    public static void main(String[] args) {
        String filePath = "F:\\股指数据金烨\\提取的数据\\IM\\20250401\\IM2506.csv";
        Map<String, Double> priceMap = createPriceMap(filePath);

        // 验证结果
        System.out.println("Total entries: " + priceMap.size());
        priceMap.forEach((k, v) -> System.out.println(k + " => " + v));
    }
}
